package org.water.garden.provider;


import android.content.*;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.Im.Account;
import android.text.TextUtils;
import android.util.Log;

import java.util.HashMap;

/**
 * Provides access to a database of notes. Each note has a title, the note
 * itself, a creation date and a modified data.
 *
 */
public class ImProvider extends ContentProvider {

    private SQLiteDatabase mDB;

    private static final String TAG = "AccountProvider";
    private static final String DATABASE_NAME = "salon.db";
    private static final int DATABASE_VERSION = 1;

    private static HashMap<String, String> ACCOUNTS_LIST_PROJECTION_MAP;

    private static final int ACCOUNTS = 1;
    private static final int ACCOUNT_ID = 2;

    private static final UriMatcher URL_MATCHER = null;

    private static class DatabaseHelper extends SQLiteOpenHelper {

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE accounts (_id INTEGER PRIMARY KEY,"
                    + "account TEXT," + "password TEXT," + "protocol INTEGER,"
                    + "status INTEGER," + "config TEXT," + "created INTEGER,"
                    + "modified INTEGER" + ");");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS accounts");
            onCreate(db);
        }
    }

    @Override
    public boolean onCreate() {
        DatabaseHelper dbHelper = new DatabaseHelper();
        mDB = dbHelper.openDatabase(getContext(), DATABASE_NAME, null, DATABASE_VERSION);
        return (mDB == null) ? false : true;
    }

    @Override
    public Cursor query(Uri url, String[] projection, String selection,
            String[] selectionArgs, String sort) {
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

        switch (URL_MATCHER.match(url)) {
        case ACCOUNTS:
        	Log.i(TAG, "GET ACCOUNTS");
            qb.setTables("accounts");
            qb.setProjectionMap(ACCOUNTS_LIST_PROJECTION_MAP);
            break;

        case ACCOUNT_ID:
            qb.setTables("accounts");
            qb.appendWhere("_id=" + url.getPathSegments().get(1));
            break;

        default:
            throw new IllegalArgumentException("Unknown URL " + url);
        }

        Cursor c = qb.query(mDB, projection, selection, selectionArgs, null, null, null);
        c.setNotificationUri(getContext().getContentResolver(), url);
        return c;
    }

    @Override
    public String getType(Uri url) {
        switch (URL_MATCHER.match(url)) {
        case ACCOUNTS:
            return "vnd.android.cursor.dir/vnd.google.im.account";

        case ACCOUNT_ID:
            return "vnd.android.cursor.item/vnd.google.im.account";

        default:
            throw new IllegalArgumentException("Unknown URL " + url);
        }
    }

    @Override
    public Uri insert(Uri url, ContentValues initialValues) {
        long rowID;
        ContentValues values;
        if (initialValues != null) {
            values = new ContentValues(initialValues);
        } else {
            values = new ContentValues();
        }

        if (URL_MATCHER.match(url) != ACCOUNTS) {
            throw new IllegalArgumentException("Unknown URL " + url);
        }

        Long now = Long.valueOf(System.currentTimeMillis());

        rowID = mDB.insert("accounts", "account", values);
        if (rowID > 0) {
            Uri uri = ContentUris.withAppendedId(Account.CONTENT_URI, rowID);
            getContext().getContentResolver().notifyChange(uri, null);
            return uri;
        }

        throw new SQLException("Failed to insert row into " + url);
    }

    @Override
    public int delete(Uri url, String where, String[] whereArgs) {
        int count;
        long rowId = 0;
        switch (URL_MATCHER.match(url)) {
        case ACCOUNTS:
            count = mDB.delete("note_pad", where, whereArgs);
            break;

        case ACCOUNT_ID:
            String segment = url.getPathSegments().get(1);
            rowId = Long.parseLong(segment);
            count = mDB
                    .delete("notes", "_id="
                            + segment
                            + (!TextUtils.isEmpty(where) ? " AND (" + where
                                    + ')' : ""), whereArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URL " + url);
        }

        getContext().getContentResolver().notifyChange(url, null);
        return count;
    }

    @Override
    public int update(Uri url, ContentValues values, String where, String[] whereArgs) {
        int count;
        switch (URL_MATCHER.match(url)) {
        case ACCOUNTS:
            count = mDB.update("notes", values, where, whereArgs);
            break;

        case ACCOUNT_ID:
            String segment = url.getPathSegments().get(1);
            count = mDB
                    .update("notes", values, "_id="
                            + segment
                            + (!TextUtils.isEmpty(where) ? " AND (" + where
                                    + ')' : ""), whereArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URL " + url);
        }

        getContext().getContentResolver().notifyChange(url, null);
        return count;
    }
}
